package com.qingke.note.command_impl;

import java.util.List;
import java.util.regex.Pattern;
import org.apache.ibatis.session.SqlSession;
import com.qingke.note.App;
import com.qingke.note.Console;
import com.qingke.note.IDao.PasswordMapper;
import com.qingke.note.IDao.UserMapper;
import com.qingke.note.command.Command;
import com.qingke.note.pojo.Password;
import com.qingke.note.pojo.User;

public class SignupCommand extends Command {

	public SignupCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		SqlSession session = getSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		Console.println("欢迎注册");
		String username = inputUsername(userMapper);
		String keyword = inputPassword();
		
		App.getInstance().setCurrentUser(insert(username, keyword, session));
		Console.println("注册成功，已经自动登录该账户");
	}
	
	
	private User insert(String username,String keyword,SqlSession session){
		UserMapper userMapper = session.getMapper(UserMapper.class);
		PasswordMapper passwordMapper = session.getMapper(PasswordMapper.class);
		String name = Console.askInput("请输入您的名字:");
		User user = new User();
		user.setName(name);
		user.setUsername(username);
		userMapper.insert(user);
		user = userMapper.login(username);
		Password password = new Password();
		password.setPassword(keyword);
		password.setUser(user);
		passwordMapper.insert(password);
		List<Password> list = passwordMapper.selectByUser(currentUser.getId());
		for (Password password2 : list) {
			if(password2.getPassword().equals(keyword)){
				password = password2;
				break;
			}
		}
		user.setPassword(password);
		return user;
	}
	
	private String inputPassword() {
		String password = Console.askInput("请输入密码");
		while(true){
			try {
				valid(password);
			} catch (Exception e) {
				Console.println(e.getMessage());
				password = Console.askInput("请重新输入密码");
				continue;
			}
			return password;
		}
	}

	private String inputUsername(UserMapper userMapper) {
		String username = Console.askInput("请输入您要注册的用户名");
		while(true){
			if(userMapper.login(username)!= null){
				Console.println("该用户名已经被注册");
				username = Console.askInput("请重新输入一个用户名");
				continue;
			}
			Console.println("恭喜，该用户名可用");
			return username;			
		}
	}
	
	private void valid(String password) throws Exception {
		Pattern lenPattern = Pattern.compile("[0-9a-zA-z]{6,}");
		if(!lenPattern.matcher(password).find()){
			throw new Exception(">>Error:密码长度必须大于6位");
		}
		
		Pattern numPattern = Pattern.compile("[a-zA-Z]");
		if(!numPattern.matcher(password).find()){
			throw new Exception(">>Error:密码不能为纯数字");
		}
		
		Pattern wordPattern = Pattern.compile("[0-9]");
		if(!wordPattern.matcher(password).find()){
			throw new Exception(">>Error:密码不能为纯字母");
		}
	}

}
